/*
 * Copyright (c) 2004-2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gou Pengfei
 * Date:    April. 2011
 */

#ifndef __CPU_EDGE_TOURNAMENT_TYPE_HH__
#define __CPU_EDGE_TOURNAMENT_TYPE_HH__

#include <vector>
#include <deque>

#include "base/types.hh"
#include "cpu/edge/sat_counter.hh"
#include "config/the_isa.hh"
#include "arch/isa_traits.hh"
#include "params/DerivEdgeCPU.hh"

/**
 * This is deprecated and replaced by TournamentFramework.
 * */
template<class Impl>
class TournamentTypeP
{
  public:
    typedef TheISA::BlockID BlockID;
    typedef TheISA::BTypeID BTypeID;
    typedef std::deque<Addr> PathHistory;

    enum GlobalIndexMode {
        Address,
        AddressAndPath,
        AddressAndCPath,
        AddressAndHist,
        InvalidGlobalIndexMode
    };

    enum PredictionMode {
        Global,
        Local,
        Tournament,
        InvalidPredictionMode
    };

    enum HysteresisMode {
        Symmetric,
        Asymmetric,
        InvalidHysteresisMode
    };

    /**
     * Default branch predictor constructor.
     */
    TournamentTypeP(uint64_t _localPredictorSize,
                    uint64_t _localHistoryTableSize,
                    uint64_t _localHistoryBits,
                    uint64_t _localCtrBits,
                    uint64_t _globalPredictorSize,
                    uint64_t _globalHistoryBits,
                    uint64_t _globalCtrBits,
                    uint64_t _choiceHistoryBits,
                    uint64_t _choicePredictorSize,
                    uint64_t _choiceCtrBits,
                    uint64_t _blockShiftAmt,
                    std::string _global_index_mode,
                    std::string _prediction_mode,
                    std::string _hysteresis_mode
                    );

    TournamentTypeP(DerivEdgeCPUParams *params);

    ~TournamentTypeP();

    void reset();	
    /**
     * Looks up the given block address in the branch predictor and returns
     * an exit ID of the block.  Also creates a
     * BPHistory object to store any state it will need on squash/update.
     * @param block_addr The address of the block to look up.
     * @param bp_history Pointer that will be set to the BPHistory object.
     * @return the ID of the exit of the block.
     */
    TheISA::BTypeID lookup(BlockID block_id, BlockID oldest_block_id, 
        Addr &block_addr, int addr_space_ID, ThreadID tid);   

    /**
     * Updates the branch predictor with the actual result of a branch.
     * @param branch_addr The address of the branch to update.
     * @param taken Whether or not the branch was taken.
     * @param bp_history Pointer to the BPHistory object that was created
     * when the branch was predicted.
     */
    void update(BlockID block_id, Addr &block_addr, int addr_space_id,
                              BTypeID actual_type_id,ThreadID tid);

    /**
     * Restores the global branch history on a squash.
     */
    void squash(BlockID block_id, Addr block_pc, BTypeID type_id,
            ThreadID tid);

    /**
     * Restores the global branch history on a squash.
     */
    void squash(BlockID block_id,ThreadID tid);

    uint64_t lookupGetIndex(Addr &block_PC, ThreadID tid);

    uint64_t updateGetIndex(BlockID block_id, Addr &block_PC, ThreadID tid);

    uint64_t getPathHistory(ThreadID tid);

    uint64_t getPathHistory(BlockID block_id, ThreadID tid);

  private:
    /**
     * The branch history information that is created upon predicting
     * a branch.  It will be passed back upon updating and squashing,
     * when the BP can use this information to update/restore its
     * state properly.
     */
    struct BPHistory {
        uint64_t globalHistory;
        BTypeID localPredBTypeID;
        BTypeID globalPredBTypeID;
        bool globalUsed;
    };

    struct PredictionTableEntry {
        PredictionTableEntry() : typeID(TheISA::InvalidExitType)
        { hysteresis.reset();}

	~PredictionTableEntry()
	{}

	BTypeID typeID;
        SatCounter hysteresis;
    };

    struct LFFEntry {
        uint64_t index;
	uint64_t history;
    };

    void initVars();

    GlobalIndexMode globalIndexMode;

    PredictionMode predictionMode;

    HysteresisMode hysteresisMode;

    /**
     * Returns the local history index, given a branch address.
     * @param branch_addr The branch's PC address.
     */
    inline uint64_t calcLocHistIdx(Addr &block_addr, int addr_space_ID);

    inline uint64_t calcLocPredIdx(Addr &block_addr, uint64_t history);

    inline uint64_t calcChoiPredIdx(Addr &block_addr, uint64_t history);

    inline uint64_t calcGloPredIdx(Addr &block_addr, uint64_t history,
            uint64_t path_hist);

    void updatePathHistory(PathHistory &path_history, Addr new_pc);

    void updateHysteresis(PredictionTableEntry &entry,
            BTypeID actual_type_id);

    /** Local counters. */
    std::vector<PredictionTableEntry> localCtrs;

    /** Size of the local predictor. */
    uint64_t localPredictorSize;

    /** Mask to get the proper index bits into the predictor. */
    uint64_t localPredictorMask;

    /** Array of local history table entries. */
    std::vector<uint64_t> localHistoryTable;

    /** Array of local future file. */
    std::vector<LFFEntry> localFutureFile;
	
    /** Size of the local history table. */
    uint64_t localHistoryTableSize;

    /** Number of bits for each entry of the local history table.
     *  @todo Doesn't this come from the size of the local predictor?
     */
    uint64_t localHistoryBits;

    /** Mask to get the proper local history. */
    uint64_t localHistoryMask;

    /** Number of bits for local hysteresis. */
    uint64_t localCtrBits;
	
    /** Array of counters that make up the global predictor. */
    std::vector<PredictionTableEntry> globalCtrs;

    /** Size of the global predictor. */
    uint64_t globalPredictorSize;

    /** Mask of the global predictor table. */
    uint64_t globalPredictorMask;

    /** Global history register. */
    uint64_t globalHistory[Impl::MaxThreads];

    /** Path histories of all threads, speculatively updated. */
    PathHistory pathHistoryTable[Impl::MaxThreads];

    /** Global history file. */
    std::vector<uint64_t> globalHistoryFile;

    /** Path histories of all in-flight blocks. */
    PathHistory pathHistoryFile[Impl::MaxInFlightBlockNum];

    /** Number of bits for the global history. */
    uint64_t globalHistoryBits;

    /** Mask to get the proper global history. */
    uint64_t globalHistoryMask;

    /** Number of bits for global hysteresis. */
    uint64_t globalCtrBits;

    /** Choice history register. */
    uint64_t choiceHistory[Impl::MaxThreads];

    /** Choice history file. */
    std::vector<uint64_t> choiceHistoryFile;

    /** Number of bits for the choice history. */
    uint64_t choiceHistoryBits;

    /** Mask to get the proper choice history. */
    uint64_t choiceHistoryMask;

    /** Array of counters that make up the choice predictor. */
    std::vector<SatCounter> choiceCtrs;

    /** Size of the choice predictor (identical to the global predictor). */
    uint64_t choicePredictorSize;

    /** Mask of the choice predictor table. */
    uint64_t choicePredictorMask;

    /** Number of bits of the choice predictor's counters. */
    uint64_t choiceCtrBits;

    /** Number of bits to shift the instruction over to get rid of the word
     *  offset.
     */
    uint64_t blockShiftAmt;

    /** Threshold for the counter value; above the threshold is taken,
     *  equal to or below the threshold is not taken.
     */
    uint64_t threshold;

    /** Threshold for global/local predictor; above the threshold we
     * can update the entry, equal to or below the threshold we can
     * not update.*/
    uint64_t glThreshold;

    /** Type id bits. */
    int typeIdBits;

    /** Type id mask. */
    uint64_t typeIdMask;
};

#endif // __CPU_EDGE_TOURNAMENT_TYPE_HH__
